#!/usr/bin/python
"""Base library and utilities for manipulating BGG geeklist XML files.

"""

__author__ = "Bruce Murphy"

import codecs
import cookielib
import csv
import datetime
import dateutil.parser
import dateutil.tz
import re
import sys
import xml.etree.ElementTree as ET
import StringIO
import urllib
import urllib2

def ReadAndParseXML(xml_filename):
  """Wrapper around our XML reading library call."""
  tree = ET.parse(xml_filename)
  return tree.getroot()


def BasicXMLReport(xmlroot):
  """Prints out a simple indented XML structure diagram"""

  def PrintElem(element, indent):
    "Prints a single element with indentation, recurses over children."
    if "objectname" in element.attrib:
      name = ":  " + element.attrib["objectname"]
    else:
      name = ""
    print indent + element.tag + name
    for child in element:
      PrintElem(child, indent + "  ")

  PrintElem(xmlroot, "")


def HasCommentsBy(item, bgguser):
  "Comments on a geeklist item from bgguser exist."
  bgguser = bgguser.lower()
  for child in item:
    if not child.tag == "comment":
      continue

    if child.attrib["username"].lower() == bgguser:
      return True

  return False


def ParseXMLDate(datestring):
  "Parses an XML date and returns a datetime object"
  return dateutil.parser.parse(datestring)


def GetItemBody(item):
  "Returns the body of an item."
  for child in item:
    if child.tag == "body":
      return child.text

  return ""


def PostingUsersReport(xmlroot):
  """Parses geeklist and returns a list of all posting users."""
  posting_users = []

  for item in xmlroot:
    if item.tag != "item":
      continue

    posting_users.append(item.attrib["username"])
  return posting_users


def PostGeeklistComment(itemid, comment, cookies = None):
  """Posts a comment to the specified item on a geeklist.

  Arguments: A CookieJar object containing a valid set of BGG login cookies.
  """
  itemid = str(itemid)

  # for the moment, we'll assume that the file "bgg-cookies.txt"
  # exists in the current working directory and contains a valid set
  # of BGG login cookies

  cookies = cookielib.MozillaCookieJar("bgg-cookies.txt")
  cookies.load()

  # construct a geeklist item post.
  opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
  form_data = { "action": "save",
               "objectid": itemid,
               "objecttype": "listitem",
               "geek_link_select_1": "",
               "sizesel": 10,
               "body": comment,
               "subscribe[listitem]": itemid,
               "ajax": "1",
               }
  data = urllib.urlencode(form_data)
  response = opener.open("http://boardgamegeek.com/geekcomment.php", data)
  if str(response.getcode()).startswith("2"):
    print "Wrote comment to item %s" % itemid
  else:
    print "Failed to write trade code to item %s" % itemid

def main(argv):

  PostGeeklistComment(3843042, "C'est ne pas une trade code")
  sys.exit(1)

  if len(argv) < 2:
    print "Usage: geeklist_tool.py geeklist command [ args ]"
    print "available commands:"
    print "  posting_users: all users who posted an item"
    sys.exit(1)

  xml_filename = argv[0]
  command = argv[1]
  geeklist_data = ReadAndParseXML(xml_filename)

  if command == "posting_users":
    print "\n".join(PostingUsersReport(geeklist_data))
  else:
    print "unknown commmand:", command


if __name__ == "__main__":
  main(sys.argv[1:])
